package com.alex.chat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;

import com.alex.chat.message.Message;
import com.alex.chat.message.TextMessage;
import com.google.gson.Gson;

@WebServlet(urlPatterns = {"/service"}, asyncSupported = true)
public class ChatServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Collection<Message> messages = new ArrayList<Message>();
		messages.add(new TextMessage("Hello!!!"));
		messages.add(new TextMessage("How are you?"));
		
		Gson gson = new Gson();
		String json = gson.toJson(messages);
		String jsonp = request.getParameter("callback") + "(\"" + StringEscapeUtils.escapeJavaScript(json) + "\");";
		response.setCharacterEncoding("utf-8");
		response.getOutputStream().write(jsonp.getBytes("utf-8"));
	}

}
